<? 
require_once("../includes/db.php"); 
require_once("../includes/utils.php"); 

$db = new DB;

$resultset = $db->query ("  SELECT 
                                message_of_the_day,
                                appliances,
                                advance_status,
   		                        last_queried,
        		                last_updated_on_server,
                 	            last_updated_on_device,
                 	            max_temp,
                 	            gpio_1,
                 	            gpio_2,
                 	            gpio_3
                            FROM
                                heating");

if (! $resultset  ||  1 != mysql_num_rows ($resultset))
{
    ?>
    Sorry, a DB error occurred when getting the basic 'heating' details: <?=$db->getLastError()?>
    <?
    return;
}




// Success!
$row = mysql_fetch_array($resultset);

$days = array();

$messageOfTheDay = $row["message_of_the_day"];
$appliances = $row["appliances"];
$advanceStatus = $row["advance_status"];
$lastQueried = $row["last_queried"];
$lastUpdatedOnServer = $row["last_updated_on_server"];
$lastUpdatedOnDevice = $row["last_updated_on_device"];
$maxTemp = $row["max_temp"];
$gpio1 = $row["gpio_1"];
$gpio2 = $row["gpio_2"];
$gpio3 = $row["gpio_3"];



$resultset = $db->query ("  SELECT
                                day,
                                window1_start,
                                window1_end,
                                window2_start,
                                window2_end,
                                window3_start,
                                window3_end
                            FROM
                                windows
                            ORDER BY
                                day ASC");


if (! $resultset  ||  7 != mysql_num_rows ($resultset))
{
    ?>
    Sorry, a DB error occurred when getting the 'window' details: <?=$db->getLastError()?>
    <?
    return;
}

// Success!
$days = array();

while ($row = mysql_fetch_array($resultset))
{
    $day = $row["day"];
        
    $days[$day] = array("window1_start" => $row["window1_start"],
                        "window1_end"   => $row["window1_end"],
                        "window2_start" => $row["window2_start"],
                        "window2_end"   => $row["window2_end"],
                        "window3_start" => $row["window3_start"],
                        "window3_end"   => $row["window3_end"]);
}                        
                           
//
//  END OF INITIAL DB QUERIES
// 




//
//  VALIDATION AND SAVING
//
$dayNames = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
$warnings = array();
$isValid = true;

if (strlen($_POST["advance"]) > 0)
{
    // Validation    
    $warnings[] = validateByRegex($_POST["motd"], "/^.{1,16}$/", "Message of the day must be 16 characters or less");
    
    for ($i=0; $i < 7; $i++)
    {    
        for ($j=0; $j < 3; $j++)
        {
            $isWindowValid = true;
            $startTime = $_POST["day" . $i . "_window" . ($j+1) . "_start"];
            $endTime   = $_POST["day" . $i . "_window" . ($j+1) . "_end"];
            
            $startWarning = validateByRegex($startTime, 
                                            "/^[0-2][0-9]:[0-5][0-9]$/", 
                                            "Start time for " . $dayNames[$i] . "'s window " . ($j+1) . " must be in the form hh:mm");
                                            
            $endWarning   = validateByRegex($endTime,
                                            "/^[0-2][0-9]:[0-5][0-9]$/", 
                                            "End time for " . $dayNames[$i] . "'s window " . ($j+1) . " must be in the form hh:mm");
            
            if (strlen($startWarning) > 0)
            {
                $warnings[] = $startWarning;
                $isWindowValid = false;
            }
            if (strlen($endWarning) > 0)
            {
                $warnings[] = $endWarning;
                $isWindowValid = false;
            }
            if ($isWindowValid  &&  0 == strlen($startWarning)  &&  0 == strlen($endWarning))
            {
                if (timeToInt($startTime) > 240)
                {
                    $warnings[] = "Start time for " . $dayNames[$i] . "'s window " . ($j+1) . " must be between 00:00 and 24:00";
                    $isWindowValid = false;
                }
                if (timeToInt($endTime) > 240)
                {
                    $warnings[] = "End time for " . $dayNames[$i] . "'s window " . ($j+1) . " must be between 00:00 and 24:00";
                    $isWindowValid = false;
                }
                if (timeToInt($endTime) < timeToInt($startTime))
                {
                    $warnings[] = "Start time for " . $dayNames[$i] . "'s window " . ($j+1) . " must be after the start time";
                    $isWindowValid = false;
                }                
            }
        }
    }
    
    foreach ($warnings as $warning)
    {
        if (strlen($warning) > 0)
        {
            $isValid = false;
        }
    }
    
	$messageOfTheDay = $_POST["motd"];
	$appliances = $_POST["appliances"];		
	$advanceStatus = $_POST["advance"];		
	$maxTemp = $_POST["maxTemp"];
	$gpio1 = $_POST["gpio1"];
	$gpio2 = $_POST["gpio2"];
	$gpio3 = $_POST["gpio3"];
	
    for ($i=0; $i < 7; $i++)
    {
        for ($j=0; $j < 3; $j++)
        {
            $days[$i]["window" . ($j+1) . "_start"] = timeToInt($_POST["day" . $i . "_window" . ($j+1) . "_start"]);
            $days[$i]["window" . ($j+1) . "_end"]   = timeToInt($_POST["day" . $i . "_window" . ($j+1) . "_end"]);        
        }
    }
    
    
    
    // Saving
    if ($isValid)
    {    
        $resultset = $db->query ("UPDATE heating SET 
                                      message_of_the_day = '" . makeSafeForDB($messageOfTheDay) . "', 
                                      appliances         = " . makeSafeForDB($appliances) . ",
                                      advance_status     = " . makeSafeForDB($advanceStatus) . ",
                                      max_temp           = " . makeSafeForDB($maxTemp) . ",
                                      gpio_1             = " . makeSafeForDB($gpio1) . ",
                                      gpio_2             = " . makeSafeForDB($gpio2) . ",
                                      gpio_3             = " . makeSafeForDB($gpio3));
        
        // TODO - check for save success
        for ($i=0; $i < 7; $i++)
        {
            $resultset = $db->query ("UPDATE windows SET
                                          window1_start = " . makeSafeForDB($days[$i]["window1_start"]) . ", 
                                          window1_end   = " . makeSafeForDB($days[$i]["window1_end"]) . ", 
                                          window2_start = " . makeSafeForDB($days[$i]["window2_start"]) . ", 
                                          window2_end   = " . makeSafeForDB($days[$i]["window2_end"]) . ", 
                                          window3_start = " . makeSafeForDB($days[$i]["window3_start"]) . ", 
                                          window3_end   = " . makeSafeForDB($days[$i]["window3_end"]) . "
                                      WHERE
                                          day = " . $i);
        }                                  
    }
}

date_default_timezone_set("Europe/London");
$sTime = date("H:i");
?>
Time is: <?=h($sTime)?>
<p/>
Last queried is: <?=h($lastQueried)?>
<p/>
Last updated on server is: <?=h($lastUpdatedOnServer)?>
<p/>
Last updated on device is: <?=h($lastUpdatedOnDevice)?>
<p/>
<?
if (! $isValid)
{
    ?>
    <hr/>
    <div style="color: red">
        <?
        foreach ($warnings as $warning)
        {
            if (strlen($warning) > 0)
            {
                ?>
                <?=h($warning)?>
                <p/>
                <?
            }
        }
        ?>
    </div>
    <hr/>
    <?
    
}
?>
<form action="form.php" method="post">

	Message of the Day:
	<input type="text" name="motd" value="<?=h($messageOfTheDay)?>"/>
<p/>
	Max temperature:
	<input type="text" name="maxTemp" value="<?=h($maxTemp)?>"/>
<p/>
	Current appliances:
	<select name="appliances">
		<option value="0" <?=0 == $appliances ? "selected" : ""?>>Off</option>
		<option value="1" <?=1 == $appliances ? "selected" : ""?>>Hot Water Only</option>
		<option value="2" <?=2 == $appliances ? "selected" : ""?>>Hot Water and Central Heating</option>
	</select>
<p/>
	Current 'advance' setting:
	<select name="advance">
		<option value="0" <?=0 == $advanceStatus ? "selected" : ""?>>Normal</option>
		<option value="1" <?=1 == $advanceStatus ? "selected" : ""?>>+1 hour</option>
		<option value="2" <?=2 == $advanceStatus ? "selected" : ""?>>Advance</option>
	</select>
<p/>
	GPIO 1:
	
	<select name="gpio1">
		<option value="0" <?=0 == $gpio1 ? "selected" : ""?>>Off</option>
		<option value="1" <?=0 != $gpio1 ? "selected" : ""?>>On</option>
	</select>
<p/>
	GPIO 2:
	<select name="gpio2">
		<option value="0" <?=0 == $gpio2 ? "selected" : ""?>>Off</option>
		<option value="1" <?=0 != $gpio2 ? "selected" : ""?>>On</option>
	</select>
<p/>
	GPIO 3:
	<select name="gpio3">
		<option value="0" <?=0 == $gpio3 ? "selected" : ""?>>Off</option>
		<option value="1" <?=0 != $gpio3 ? "selected" : ""?>>On</option>
	</select>
<p/>
<table>
    <tr>
        <th rowspan="2">Day</th>
        <th colspan="2">Window 1</th>
        <th colspan="2">Window 2</th>
        <th colspan="2">Window 3</th>
    </tr>
    <tr>
        <th>Start</th>
        <th>End</th>
        <th>Start</th>
        <th>End</th>
        <th>Start</th>
        <th>End</th>
    </tr>
    <?
    
    for ($i=0; $i<7; $i++)
    {        
    
        ?>
        <tr>
            <td><?=$dayNames[$i]?></td>
            <td><input type="text" name="day<?=$i?>_window1_start" class="window" value="<?=h(intToTime($days[$i]["window1_start"]))?>"/></td>
            <td><input type="text" name="day<?=$i?>_window1_end"   class="window" value="<?=h(intToTime($days[$i]["window1_end"]))?>"  /></td>
            <td><input type="text" name="day<?=$i?>_window2_start" class="window" value="<?=h(intToTime($days[$i]["window2_start"]))?>"/></td>
            <td><input type="text" name="day<?=$i?>_window2_end"   class="window" value="<?=h(intToTime($days[$i]["window2_end"]))?>"  /></td>
            <td><input type="text" name="day<?=$i?>_window3_start" class="window" value="<?=h(intToTime($days[$i]["window3_start"]))?>"/></td>
            <td><input type="text" name="day<?=$i?>_window3_end"   class="window" value="<?=h(intToTime($days[$i]["window3_end"]))?>"  /></td>
        </tr>
        
        <?
    }
    ?>
</table>
<p/>
    <input type="submit"/> | <a href="form.php">Cancel/Refresh</a>
</form>

</body>
</html>
